package com.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pojo.Permission;
import com.pojo.Role;
import com.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/*实现安全认证和授权
* 这个类,security自己的配置文件dubbo也要扫到
* */
@Component
public class SpringSecurityUserService implements UserDetailsService {
   @Reference
   private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.pojo.User user = userService.findByUserName(s);

        if (user==null){
            return null;
        }
        //System.out.println(user);
        //说明用户是存在的
       List<GrantedAuthority> list = new ArrayList<>();
        //取出里面权限和角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //取出角色
            String keyword = role.getKeyword();
            list.add(new SimpleGrantedAuthority(keyword));
            //取出权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //三个参数都已凑齐,开始返回
        User user1 = new User(s, user.getPassword(), list);
        return user1;
    }
}
